package zhaomh.zlogin.Commands;

import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import zhaomh.zlogin.*;

import java.util.List;

public class RegisterCommand implements CommandExecutor {

    PlayerTools player;

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!(sender instanceof Player))
            return false;

        player = new PlayerTools((Player) sender);

        if (PlayerData.isPlayerInList(player.getPlayer())) {
            player.sendPluginMessage(Language.get("login.failure.already_has"));
            return true;
        }

        if (args.length != 2){
            player.sendPluginMessage(Language.get("register.correct_formatting"));
            return true;
        }

        if (PlayerData.isPlayerInList(player.getPlayer())) {

            return true;
        }

        List<String> players = Tools.getKeysAtPath(Data.data, "players");

        if (players != null && players.contains(player.getName())) {
            player.sendPluginMessage(Language.get("register.failure.already_has"));
            return true;
        }

        if (args[0].getBytes().length < Data.config.getInt("password.min_length")) {
            player.sendPluginMessage(Language.get("register.failure.short"));
            return true;
        }

        if (args[0].getBytes().length > Data.config.getInt("password.max_length")) {
            player.sendPluginMessage(Language.get("register.failure.long"));
            return true;
        }

        if (!args[0].equals(args[1])) {
            player.sendPluginMessage(Language.get("register.failure.differ"));
            return true;
        }

        Data.data.set("players."+player.getName()+".password",args[0]);
        Data.saveConfigs();

        PlayerData.addPlayer(player.getPlayer());
        player.sendPluginMessage(Language.get("register.success"));
        player.sendPluginMessage(Language.get("login.success"));
        return true;
    }
}
